﻿using System;
using System.Net.NetworkInformation;
using System.Threading;

namespace HobSoft.SoccerBet2014.Common.Net
{
    public class PingTask : IDisposable
    {
        private Timer timer;
        private Ping ping;
        private PingOptions pingOptions;
        private int pingTimeout = 1000;
        private int timerPeriod = 1000;
        public event EventHandler<PingReply> OnPingReply;
        public bool OnPinging { get; protected set; }
        public string HostOrAddress { get; protected set; }
        public PingTask()
        {
            timer = new Timer(new TimerCallback(Timer_Callback), null, Timeout.Infinite, timerPeriod);
            ping = new Ping();
            pingOptions = new PingOptions();
            pingOptions.DontFragment = true;
            ping.PingCompleted += Ping_PingCompleted;
        }

        private void Timer_Callback(object state)
        {
            if (OnPinging)
            {
                timer.Change(Timeout.Infinite, Timeout.Infinite);
                byte[] buffer = new byte[32];
                PingReply reply = ping.Send(HostOrAddress, pingTimeout, buffer, pingOptions);
                RaisePingReply(reply);
                timer.Change(timerPeriod, timerPeriod);
            }
        }

        private void Ping_PingCompleted(object sender, PingCompletedEventArgs e)
        {

        }

        private void RaisePingReply(PingReply reply)
        {
            if (OnPingReply != null)
                OnPingReply(this, reply);
        }

        public void Start(string hostOrAddress)
        {
            OnPinging = true;
            HostOrAddress = hostOrAddress;
            timer.Change(0, timerPeriod);
        }

        public void Stop()
        {
            OnPinging = false;
            timer.Change(Timeout.Infinite, timerPeriod);
        }

        public void Dispose()
        {
            if (ping != null)
            {
                (ping as IDisposable).Dispose();
            }
            if (timer != null)
            {
                timer.Dispose();
            }
        }
    }
}
